import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:media_kit_video/media_kit_video.dart';

import '../../../../components/base_page/base_error_widget.dart';
import '../../../../components/image_view.dart';
import '../../../../generate/app_image_path.dart';
import '../../../../services/app_service.dart';
import '../../../../utils/color.dart';
import '../../../../utils/extension.dart';
import '../../../player/views/av_player_loading.dart';
import 'media_kit_short_controls.dart' as short;
import 'short_v_p_cell_controller.dart';
import 'short_v_p_desc_area.dart';
import 'short_v_p_operation_area.dart';
import 'short_v_p_top_area.dart';
import 'short_video_model.dart';

// ignore: must_be_immutable
class ShortVPCell extends StatelessWidget {
  final ShortVideoModel video;
  final ShortVPCellController controller;

  const ShortVPCell(this.video, {super.key, required this.controller});

  ///根控制器的tag
  String get mainControllerTag => controller.mode!.index.toString();

  Widget _buildPlayOrPauseBtn() {
    return Obx(
      () => Visibility(
        visible: controller.videoPaused.value,
        child: Image.asset(
          AppImagePath.short_short_play_btn,
          width: 40.w,
          height: 40.w,
          fit: BoxFit.cover,
        ).onTap(controller.togglePlayOrPause),
      ),
    );
  }

  Widget _buildPlayerInitState() {
    return Obx(() {
      final state = controller.playerInitialized.value;
      if (state == VPInitState.none) {
        return const AvPlayerLoading();
      } else if (state == VPInitState.error) {
        return BaseErrorWidget(onTap: () => controller.initPlayer());
      } else {
        return const SizedBox.shrink();
      }
    });
  }

  Widget _buildCover(BuildContext context) {
    if (controller.playerInitialized.value == VPInitState.none) {
      return Positioned.fill(
          child: Center(
        child: ImageView(src: video.detail?.vCover ?? ''),
      ));
    }
    return const SizedBox.shrink();
  }

  Widget _buildPlayer(BuildContext context) {
    var w = video.detail?.width ?? Get.width;
    if (w == 0) {
      w = Get.width;
    }
    var h = video.detail?.height ?? Get.height;
    if (h == 0) {
      h = Get.height;
    }
    final asp = w / h;
    const themColor = COLOR.white;
    const themData = MaterialVideoControlsThemeData(
      seekBarPositionColor: themColor,
      seekBarThumbColor: themColor,
    );
    final controls = MaterialVideoControlsTheme(
      normal: themData,
      fullscreen: themData,
      child: short.MediaKitShortControls(
        buildContext: context,
        viewSize: Size(Get.width, Get.height),
        texturePos: Rect.fromLTWH(0, 0, Get.width, Get.height),
        playerTitle: video.detail?.title ?? '',
      ),
    );
    return SizedBox(
      width: 1.sw,
      height: 1.sh,
      child: Video(
        key: Key('${video.detail?.videoId ?? 0}'),
        filterQuality: FilterQuality.none,
        fill: Colors.transparent,
        width: Get.width,
        height: 1.sh,
        controls: (state) {
          return controls;
        },
        controller: controller.playerVC!,
        aspectRatio: asp,
        fit: BoxFit.fitWidth,
      ),
    );
  }

  Widget _buildOperation() {
    return ShortVPOperationArea(
      controller.video.detail!,
      topHeight: 100,
      onTapUnmute: controller.onTapUnmute,
      webMuted: controller.webVolume.value != 100,
    );
  }

  //中间区域， 左下广告，视频标题， 右边操作，右边广告
  Widget _buildLogicLayer() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Expanded(child: ShortVPDescArea(controller.video.detail!)),
        40.horizontalSpace,
        _buildOperation(),
      ],
    ).marginLeft(14.w);
  }

  Widget _buildTopAdLayer() {
    return Obx(() {
      if (Get.find<AppService>().shortShowAd) {
        return const ShortVPTopArea();
      }
      return const SizedBox.shrink();
    });
  }

  Widget _buildBody(BuildContext context) {
    const appbarHeight = 46;
    const seekBarHeight = 45;
    final bottomHeight = ScreenUtil().bottomBarHeight + seekBarHeight;
    return Stack(
      children: [
        const SizedBox.expand(),
        _buildCover(context),
        // 播放器
        _buildPlayer(context),
        // videoPlayer initialize
        Positioned.fill(child: Center(child: _buildPlayerInitState())),
        // 暂停/播放
        Positioned.fill(child: Center(child: _buildPlayOrPauseBtn())),
        // 顶部广告放下吗， 关闭按钮再LogicLayer
        Positioned.fill(
          top: ScreenUtil().statusBarHeight + appbarHeight,
          child: _buildTopAdLayer(),
        ),
        Positioned.fill(
          top: ScreenUtil().statusBarHeight + appbarHeight,
          bottom: bottomHeight,
          child: _buildLogicLayer(),
        )
      ],
    ).onTap(() {
      controller.togglePlayOrPause();
    });
  }

  @override
  Widget build(BuildContext context) {
    controller.init(video);
    return controller.obx(
      (_) => _buildBody(context),
      onLoading: const AvPlayerLoading(),
      onError: (_) => BaseErrorWidget(
        onTap: () => controller.waitLoadingDetail(forceRetry: true),
      ),
    );
  }
}
